<!--
 * @Author: Charsen
 * @Date: 2025-07-24 08:33
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-31 15:42:21
 * @Description: 
-->
<template>
  <Content>
    <SearchFormer
      ref="searchBoxRef"
      class="mb-10px"
      :data="searchFormer.data"
      :fields="searchFormer.fields"
      @on-confirm="handleSearch"
      @on-reset="handleSearch"
    />
    <div class="body-container">
      <!-- 角色管理组件 -->
      <Roles
        v-model:tree-data="roleList"
        :current-role="role"
        @refresh="fetchData"
        @role-selected="handleRoleSelected"
      />

      <div class="right-container">
        <!-- 人员管理组件 -->
        <Personnels
          v-if="role.id"
          v-model:personnels="personnels"
          :current-role="role"
          @refresh="fetchData"
        />
        <!-- 权限管理组件 -->
        <Actions
          v-if="role.id"
          :current-role="role"
          :all-actions="allActions"
          @refresh="fetchData"
        />
      </div>
    </div>
  </Content>
</template>

<script setup lang="ts">
  import { api } from '#/api'
  import { Http } from '#/utils/http'

  defineOptions({
    name: 'Authorization',
  })

  const roleList = ref([])
  const allActions = ref([])
  const personnels = ref([])
  const role = ref<any>({})
  const searchBoxRef = ref()

  const searchFormer = ref({
    data: {},
    fields: [],
  })

  const handleRoleSelected = (selectedRole: any) => {
    role.value = selectedRole
    fetchData()
  }

  const handleSearch = (data: any) => {
    searchFormer.value.data = data
    role.value = {}
    fetchData()
  }

  const fetchData = () => {
    Http.Get(api.Auth.index, {
      params: { role_id: role.value.id, ...searchFormer.value.data },
    }).then((res: any) => {
      role.value = res.data
      allActions.value = res.actions
      roleList.value = res.roles
      personnels.value = res.personnels
      if (
        Object.prototype.hasOwnProperty.call(res, 'form_widgets') &&
        searchFormer.value.fields.length === 0
      ) {
        searchFormer.value.fields = res.form_widgets
        searchFormer.value.data = {}
      }
    })
  }

  onMounted(() => {
    fetchData()
  })
</script>

<style lang="scss" scoped>
  .body-container {
    display: flex;
    flex-direction: row;
  }

  .right-container {
    flex: 1 1 auto;
    align-self: stretch;
    border-left: 1px solid #ebeef5;
  }
</style>
